package com.example.springboot.controller;

import com.example.springboot.entity.SelfServiceOrder;
import com.example.springboot.service.SelfServiceOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/self-service-orders")
public class SelfServiceOrderController {

    @Autowired
    private SelfServiceOrderService selfServiceOrderService;

    @GetMapping
    public ResponseEntity<Map<String, Object>> findAll(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String orderType, // 新增订单类型筛选
            HttpServletRequest request) {
        String role = request.getHeader("Role");
        String username = request.getHeader("Username");

        List<SelfServiceOrder> orders = selfServiceOrderService.findAll(page, size, role, username, status, orderType);
        int total = selfServiceOrderService.getTotalOrders(role, username, status, orderType);

        Map<String, Object> response = new HashMap<>();
        response.put("data", orders);
        response.put("total", total);

        return ResponseEntity.ok(response);
    }

    @GetMapping("/{orderId}")
    public ResponseEntity<SelfServiceOrder> findById(
            @PathVariable Integer orderId,
            HttpServletRequest request) {
        String role = request.getHeader("Role");
        String username = request.getHeader("Username");

        SelfServiceOrder order = selfServiceOrderService.findById(orderId, role, username);
        return ResponseEntity.ok(order);
    }

    @DeleteMapping("/{orderId}")
    public ResponseEntity<Void> deleteById(
            @PathVariable Integer orderId,
            HttpServletRequest request) {
        String role = request.getHeader("Role");
        String username = request.getHeader("Username");

        selfServiceOrderService.deleteById(orderId, role, username);
        return ResponseEntity.noContent().build();
    }
}